// import initCalendar, {getSelectedDay} from '../../component/calendar/main.js';
let app = getApp();
// let current_time = Date.parse(new Date());
const conf = {
  data: {
    isHide: false,
    showModal: false,
    user: {},
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    colorArrays: ["#85B8CF", "#90C652", "#D8AA5A", "#FC9F9D", "#0A9A84", "#61BC69", "#12AEF3", "#E29AAD"],
    weekList: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20],
    weekIndex: 0,
    termArray: [],
    termIndex: 0,
    current_time: '',
    kctitle: '',
    place: '',
    content: '',
    week: 1,
    xingqi: '',
    jieci: '',
    changdu: '',
    remindtime: '',
    flag: '',
    scheduleId: '',
    termId: 1,
    name: ''
  },

  onLoad: function() {
    let that = this;
    var date = new Date();
    var Y = date.getFullYear();
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
    var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
    var H = date.getHours() < 10 ? '0' + date.getHours() : date.getHours();
    var M1 = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes();
    this.setData({
      current_time: Y + '-' + M + '-' + D,
      time1: H + ':' + M1,
      remindTime: H + ':' + M1
    })

    // 查看是否授权
    wx.getSetting({
        success: function(res) {
          if (res.authSetting['scope.userInfo']) {
            app.globalData.userInfo = wx.getStorageSync('userInfo');
            wx.getUserInfo({
              success: res => {
                // 可以将 res 发送给后台解码出 unionId
                wx.login({
                  success(res_) {
                    if (res_.code) {
                      console.log(res_.code);
                      // 发起网络请求
                      wx.request({
                        url: app.globalData.url + '/user/userlogin',
                        method: 'POST',
                        header: {
                          'content-type': 'application/x-www-form-urlencoded'
                        },
                        data: {
                          code: res_.code,
                          nickName: res.userInfo.nickName,
                          wximg: res.userInfo.avatarUrl
                        },
                        success: result => {
                          console.log("已经授权的登录")
                          console.log(result.data)
                          app.globalData.userInfo = result.data;
                          console.log(app.globalData)
                          console.log("今天是" + that.data.current_time)
                          that.getCurrentSchedule();
                          that.setupSocket();
                          that.getTermList();
                          that.getScheduleList();
                        }
                      });
                    } else {
                      console.log('登录失败！' + res.errMsg)
                    }
                  }
                })

              }
            })

          } else {
            // 用户没有授权
            // 改变 isHide 的值，显示授权页面
            that.setData({
              isHide: true
            });
          }
        }
      }),
      that.webSocketService();
  },

  setupSocket: function() {
    // 创建Socket
    wx.connectSocket({
      url: 'ws://localhost:8080/ws/asset',
      // url: 'wss://www.cheerylab.cn/ws/asset',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function(ws_res) {
        console.log('WebSocket连接创建', ws_res);
        // if (that.data.flag == true && that.data) {
        //   if (options.realtion == "0" && options.id != wx.getStorageSync('open_id')) {
        //     that.createRelation(options.id, wx.getStorageSync('open_id'));
        //   } else {
        //     that.createRelation(wx.getStorageSync('open_id'), options.id);
        //   }
        // }
      },
      fail: function(err) {
        wx.showToast({
          title: '网络异常！',
        })
        console.log(err)
      },
    });
  },

  bindGetUserInfo: function(e) {
    let that = this;
    if (e.detail.userInfo) {
      //插入登录的用户的相关信息到数据库 
      wx.login({
        success(res_) {
          if (res_.code) {
            // 发起网络请求
            wx.request({
              url: app.globalData.url + '/user/userlogin',
              method: 'POST',
              header: {
                'content-type': 'application/x-www-form-urlencoded'
              },
              data: {
                code: res_.code,
                nickName: e.detail.userInfo.nickName,
                wximg: e.detail.userInfo.avatarUrl
              },
              success: result => {
                console.log('登录成功！')
                console.log(result)
                app.globalData.userInfo = result.data;
                that.getCurrentSchedule();
                that.setupSocket();
                that.getTermList();
                that.getScheduleList();
              }
            });
          } else {
            console.log('登录失败！' + res.errMsg)
          }
        }
      })
      //授权成功后，跳转进入小程序首页 
      that.setData({
        isHide: false
      });
    } else {
      //用户按了拒绝按钮
      wx.showModal({
        title: '警告',
        content: '您点击了拒绝授权，将无法进入小程序，请授权之后再进入!!!',
        showCancel: false,
        confirmText: '返回授权',
        success: function(res) {
          // 用户没有授权成功，不需要改变 isHide 的值
          if (res.confirm) {
            console.log('用户点击了“返回授权”');
          }
        }
      });
    }
  },

  /**
   * 跳转至添加页面
   */
  addSchedule: function() {
    wx.navigateTo({
      url: '../add/add'
    })
  },
  onShow: function() {
    // initCalendar(); // 使用默认配置初始化日历
    // getSelectedDay();
    this.onLoad();
  },
  preventTouchMove: function() {},
  hideModal: function() {
    this.setData({
      showModal: false
    });
  },
  showDetail: function(e) {
    let that = this;
    console.log(e)
    that.setData({
      showModal: true,
      scheduleId: e.currentTarget.dataset.scheduleid,
      kctitle: e.currentTarget.dataset.kctitle,
      place: e.currentTarget.dataset.place,
      content: e.currentTarget.dataset.content,
      week: e.currentTarget.dataset.week,
      xingqi: e.currentTarget.dataset.xingqi,
      jieci: e.currentTarget.dataset.jieci,
      changdu: e.currentTarget.dataset.changdu,
      remindtime: e.currentTarget.dataset.remindtime,
      flag: e.currentTarget.dataset.flag
    })
  },
  modifySchedule: function(e) {
    let that = this;
    // var scheduleId = e.currentTarget.dataset.scheduleid;
    // var kctitle = e.currentTarget.dataset.kctitle;
    // var place = e.currentTarget.dataset.place;
    // var content = e.currentTarget.dataset.content;
    // var week = e.currentTarget.dataset.week;
    // var xingqi = e.currentTarget.dataset.xingqi;
    // var jieci = e.currentTarget.dataset.jieci;
    // var changdu = e.currentTarget.dataset.changdu;
    // var remindtime = e.currentTarget.dataset.remindtime;
    // var flag = e.currentTarget.dataset.flag;

    wx.navigateTo({
      url: '../modify/modify?scheduleId=' + that.data.scheduleId + '&kctitle=' + that.data.kctitle + '&place=' + that.data.place + '&content=' + that.data.content + '&week=' + that.data.week + '&xingqi=' + that.data.xingqi + '&jieci=' + that.data.jieci + '&changdu=' + that.data.changdu + '&remindtime=' + that.data.remindtime + '&flag=' + that.data.flag
    })
  },

  deleteSchedule: function(e) {
    let that = this;
    console.log("long tap")
    wx.showModal({
      title: '删除该课程',
      content: '将本节次的所有该课程删除',
      confirmText: "删除",
      cancelText: "取消",
      success: function(res) {
        console.log(res);
        if (res.confirm) {
          console.log('用户点击确定')
          //删除该课程
          wx.request({
            url: app.globalData.url + '/deleteSchedule',
            method: 'DELETE',
            header: {
              'content-type': 'application/x-www-form-urlencoded'
            },
            data: {
              id: e.currentTarget.dataset.scheduleid
            },
            success: res => {
              wx.showToast({
                title: '删除成功',
                icon: 'success',
                duration: 3000
              });
              that.onLoad();
            },
            fail: err => {
              wx.showToast({
                title: '失败',
                icon: 'error',
                duration: 3000
              });
            }
          })
        } else {
          console.log('用户点击取消')
        }
      }
    });
  },
  bindTermChange: function(e) {
    let that = this;
    let selectedterm = that.data.termArray[e.detail.value];
    console.log(selectedterm)
    that.setData({
      termId: that.data.termArray[e.detail.value].id,
      termIndex: e.detail.value
    })
    that.getScheduleList();
  },
  bindWeekChange: function(e) {
    let that = this;
    that.setData({
      week: that.data.weekList[e.detail.value],
      weekIndex: e.detail.value
    })
    that.getScheduleList();
  },
  getTermList: function() {
    let that = this;
    wx.request({
      url: app.globalData.url + '/findTerm',
      method: 'GET',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        userId: app.globalData.userInfo.id
      },
      success: res => {
        console.log("获取用户的学期列表")
        console.log(res)
        if (res.data.length > 0) {
          let list = [];
          for (var i = 0; i < res.data.length; i++) {
            list.push({
              id: res.data[i].id,
              name: res.data[i].name
            })
          }
          that.setData({
            termArray: list
          })
        }
      }
    });
  },

  getScheduleList: function() {
    let that = this;
    wx.request({
      url: app.globalData.url + '/findSchedule',
      method: 'GET',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        termId: that.data.termId,
        week: that.data.week
      },
      success: res => {
        console.log("获取用户的课程表")
        console.log(res)
        if (res.data.length > 0) {
          let list = [];
          for (var i = 0; i < res.data.length; i++) {
            list.push({
              id: res.data[i].id,
              kctitle: res.data[i].kctitle,
              place: res.data[i].place,
              content: res.data[i].content,
              week: res.data[i].week,
              xingqi: res.data[i].xingqi,
              jieci: res.data[i].jieci,
              changdu: res.data[i].changdu,
              remindtime: res.data[i].remindtime,
              flag: res.data[i].flag
            })
          }
          that.setData({
            scheduleList: list
          })
          console.log(that.data.scheduleList)
        }
      }
    });
  },
  webSocketService: function() {
    let that = this;
    wx.onSocketMessage(function(res) {
      console.log(res)
      var obj = JSON.parse(res.data);
      console.log(obj);
      //更新session_id
      if (obj.message == "连接成功") {
        wx.request({
          url: app.globalData.url + '/user/websocket',
          method: 'POST',
          header: {
            'content-type': 'application/x-www-form-urlencoded'
          },
          data: {
            openid: app.globalData.userInfo.openid,
            sessionid: obj.session_id
          },
          success: res => {
            console.log("更新session_id成功")
          }
        })
      }
      if (obj.message.indexOf("您有一门") > -1){
        wx.showModal({
          title: '注意！',
          content: obj.message.split(":")[0],
          confirmText: "我知道了",
          showCancel: false,
          success: function (res) {
            console.log(res);
            if (res.confirm) {
              console.log('用户点击主操作')
              wx.request({
                url: app.globalData.url + '/stopschedule',
                method: 'PUT',
                header: {
                  'content-type': 'application/x-www-form-urlencoded'
                },
                data: {
                  scheduleid: obj.message.split(":")[1]
                },
                success: res => {
                  console.log("关闭任务提醒成功")
                }
              })
            } else {
              console.log('用户点击辅助操作')
            }
          }
        });
      }
    })
  },
  getCurrentSchedule: function() {
    let that = this;
    wx.request({
      url: app.globalData.url + '/userterm',
      method: 'GET',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        userId: app.globalData.userInfo.id
      },
      success: res => {

      }
    });
  }

};
Page(conf);